package org.example.state;

import com.google.common.base.Joiner;

import java.util.HashMap;
import java.util.Map;

import static org.example.state.BizException.STATE_MACHINE_TRANSITION_FAILED;

public class BaseStateMachine<STATE, EVENT> implements StateMachine<STATE, EVENT> {

    private final Map<String, STATE> stateTransitions = new HashMap<>();

    protected void putTransition(STATE origin, EVENT event, STATE target) {
        stateTransitions.put(Joiner.on("_").join(origin, event), target);
    }

    @Override
    public STATE transition(STATE state, EVENT event) {
        STATE target = stateTransitions.get(Joiner.on("_").join(state, event));
        if (target == null) {
            throw new BizException("state = " + state + " , event = " + event, STATE_MACHINE_TRANSITION_FAILED);
        }

        return target;
    }
}


